package com.zhijian.warehouse.manage.config;

import com.zhijian.entity.CommonResult;
import com.zhijian.response.annotation.Response;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;

/**
 * 自定义对外所有请求体
 *
 * @Author chengqing
 * @DateTime 2019年4月14日 下午3:43:07
 * @Version 1.0.1
 */
@SuppressWarnings("rawtypes")
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class ResponseJsonHandler implements HandlerMethodReturnValueHandler, InitializingBean {

    @Getter
    @Setter
    private HttpMessageConverter messageConverter;

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.getMethodAnnotation(Response.class) != null;
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
        mavContainer.setRequestHandled(true);
        CommonResult resp = CommonResult.success(returnValue);
        messageConverter.write(resp, MediaType.APPLICATION_JSON_UTF8, new ServletServerHttpResponse(webRequest.getNativeResponse(HttpServletResponse.class)));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (messageConverter == null) {
            throw new Exception("messageConverter is null");
        }
    }

}
